package com.glc.hms.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.glc.hms.common.tree.MenuTreeInfo;
import com.glc.hms.common.tree.TreeParser;
import com.glc.hms.system.dao.SysMenuMapper;
import com.glc.hms.system.dao.SysRoleMenuMapper;
import com.glc.hms.system.entity.SysMenu;
import com.glc.hms.system.entity.SysRoleMenu;
import com.glc.hms.system.service.ISysMenuService;
import com.glc.hms.system.service.ISysRoleMenuService;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单信息表 服务实现类
 * </p>
 *
 * @author Santa
 * @since 2019-11-26
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Autowired
    private ISysRoleMenuService roleMenuService;
    @Autowired
    private SysRoleMenuMapper roleMenuMapper;
    @Autowired
    private SysMenuMapper menuMapper;


    /**
     * 根据role获取菜单列表
     * @param userId
     * @return
     */
    @Override
    public List<MenuTreeInfo> queryMenuList(Long roleId) {



        if (roleId != null) {
            List<SysRoleMenu> sysRoleMenus = roleMenuService.queryMenuByRole(roleId);
            //汇总有权限的菜单
            if (!CollectionUtils.isEmpty(sysRoleMenus)) {
                //菜单去重
                Set<Long> menuIdSet = Sets.newHashSet();
                for (SysRoleMenu roleMenu : sysRoleMenus) {
                    menuIdSet.add(roleMenu.getMenuId());
                }

                List<SysMenu> bMenus = queryMenusByMenuIds(new ArrayList<>(menuIdSet));
                Set<Long> all = Sets.newHashSet();
                for (SysMenu menuCacheVo : bMenus) {
                    String levelCode = menuCacheVo.getLevelCode();
                    // 去掉第一个斜杠
                    String tempStr = levelCode.substring(1);
                    String[] split = tempStr.split("/");
                    for (String menuId : split) {
                        all.add(Long.valueOf(menuId));
                    }
                }
                //查询角色对应的所有的菜单
                List<SysMenu> allMenu = queryMenusByMenuIds(new ArrayList<>(all));

                // 排序
                Collections.sort(allMenu, Comparator.comparingInt(SysMenu::getSortNo));

                // 转换成前端需要的值
                List<MenuTreeInfo> menuTreeInfos = Lists.newArrayList();
                for (SysMenu cacheVo : allMenu) {
                    MenuTreeInfo info = new MenuTreeInfo();
                    BeanUtils.copyProperties(cacheVo, info);
                    info.setParentMenuId(cacheVo.getpMenuId());
                    menuTreeInfos.add(info);
                }
                // 按树形层级返回
                List<MenuTreeInfo> treeList = TreeParser.getTreeList(0L, menuTreeInfos);
                return treeList;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }


    //删除角色一级菜单
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleRoleMenu(Long roleId,Long MenuId,Integer actionId){
        QueryWrapper<SysRoleMenu> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("role_id",roleId);
        switch (actionId){
            case -1:
                QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("p_menu_id",MenuId);
                List<SysMenu> bMenus = menuMapper.selectList(queryWrapper);
                List<Long> ids = bMenus.stream().map(o -> o.getId()).collect(Collectors.toList());
                queryWrapper1.in("menu_id",ids);
                break;
            case 0:
                queryWrapper1.eq("menu_id",MenuId);
                break;
            default:
                String s = actionId.toString();
                queryWrapper1.eq("menu_id",MenuId);
                String substring = s.substring(s.length() - 1, s.length());
                queryWrapper1.eq("action_id",Long.valueOf(substring));

        }
        roleMenuMapper.delete(queryWrapper1);
    }


    //添加角色菜单权限
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addRoleMenu(Long roleId,Long[] menuAndRoleList){

        List<SysRoleMenu> SysRoleMenu = Lists.newArrayList();

        //删除旧权限
        QueryWrapper<SysRoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId);
        roleMenuMapper.delete(queryWrapper);
        //添加新权限
        for (Long menu : menuAndRoleList) {
            if(menu > 1000000 ){
                String s = menu.toString();
                String actionId = s.substring(s.length() - 1, s.length());
                String menuId = s.substring(0,s.length() - 1);
                SysRoleMenu roleMenu = new SysRoleMenu();
                roleMenu.setActionId(Integer.valueOf(actionId));
                roleMenu.setMenuId(Long.valueOf(menuId));
                roleMenu.setRoleId(roleId);
                SysRoleMenu.add(roleMenu);
            }
        }
        roleMenuService.saveBatch(SysRoleMenu);
    }




    /**
     * 批量查询菜单信息
     *
     * @param menuIds
     * @return
     */
        private List<SysMenu> queryMenusByMenuIds(List<Long> menuIds) {
        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", menuIds);
        List<SysMenu> bMenus = menuMapper.selectList(queryWrapper);
        return bMenus;
    }
	
}
